<?php
namespace Model;

class CommentHandler {

	private $database = NULL;
	const COMMENT_EMPTY = 0;
	const COMMENT_SUCCESS = 1;
	const COMMENT_FAILED = 2;

	public function __construct($a_database) {
		$this -> database = $a_database;
	}

	//Hämtar alla kommentarer
	public function getAllcomments($p_id) {
		$sql = "SELECT * FROM comment Where p_id = ? ORDER BY c_id desc";
		$stmt = $this -> database -> SqlStatement($sql);
		$stmt -> bind_param("i", $p_id);
		$stmt -> execute();
		if ($stmt -> bind_result($c_id, $p_id, $name, $comment, $date) == FALSE) {
			throw new \Exception($this -> m_mysqli -> error);
		}

		$ret = new CommentArray();
		while ($stmt -> fetch()) {
			$comments = new Comment($c_id, $p_id, $name, $comment, $date);
			$ret -> add($comments);
		}

		$stmt -> close();

		return $ret;
	}

	//Ny kommentar
	public function newComment($p_id, $name, $comment) {
		$validate = new \Common\Validator();

		if (isset($name) && isset($comment)) {

			$name1 = $validate -> filterHTML($name);
			$comment1 = $validate -> filterJavascript($comment);
			$sql = "INSERT INTO comment (p_id, name, comment) VALUES (?, ?, ?)";

			if ($name == '' || $comment == '') {
				return self::COMMENT_EMPTY;
			}

			if ($stmt = $this -> database -> SqlStatement($sql)) {
				$stmt -> bind_param('iss', $p_id, $name1, $comment1);

				$stmt -> execute();

				$stmt -> close();

				return self::COMMENT_SUCCESS;
			}
		}
		return self::COMMENT_FAILED;
	}

	//Radera kommentarer
	public function DeleteComment($c_id) {

		if (isset($c_id)) {
			$sql = "DELETE FROM comment WHERE c_id = ?";

			if ($stmt = $this -> database -> SqlStatement($sql)) {

				$stmt -> bind_param('i', $c_id);

				$stmt -> execute();

				$stmt -> close();
				return true;
			}
		}

		return false;
	}

}
